package com.totcy.atom.model;

import android.content.Context;
import android.util.Base64;

import com.totcy.atom.CommonValues;
import com.totcy.atom.bean.response.HeWeatherResponse;
import com.totcy.atom.net.HttpManager;
import com.totcy.atom.net.subscriber.BaseHttpSubscriber;
import com.totcy.atom.presenter.contract.WeatherContract;
import com.totcy.baselibrary.base.mvpbase.BaseModelImpl;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * description: 和风天气数据请求
 * autour: Totcy
 * date: 2018/1/20 14:45
 * update: 2018/1/20
 */
public class WeatherModel extends BaseModelImpl implements WeatherContract.Model {

    public WeatherModel(Context context) {
        super(context);
    }

    /**
     * 取消model层网络请求
     */
    @Override
    public void canCelRequest() {

    }

    /**
     * 从网络获取数据
     *
     * @param location
     * @param callback
     */
    @Override
    public void getWeatherInfoList(String location, final DataCallback callback) {

        HashMap<String, String> params = new HashMap<>();
        params.put("location", location);
        params.put("key", CommonValues.HEFENG_WEATHER_KEY);
        //params.put("username", CommonValues.HEFENG_WEATHER_USERID);
        //params.put("t", String.valueOf(System.currentTimeMillis()));
        //sign
        //try {
        //    params.put("sign", getSignature(params, CommonValues.HEFENG_WEATHER_KEY));
        //} catch (IOException e) {
        //    e.printStackTrace();
        //}

        HttpManager.getApiService(mContext)
                .getWeatherInfo(CommonValues.HEFENG_WEATHER_API, params)
                //线程调度
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //结果处理
                .subscribe(new BaseHttpSubscriber<HeWeatherResponse>() {
                    @Override
                    public void onSuccess(HeWeatherResponse heWeatherResponse) {
                        callback.onWeatherInfo(heWeatherResponse);
                    }

                    @Override
                    public void onError(int code, String errorMsg) {
                        callback.onDataNotAvailable(code, errorMsg);
                    }
                });

    }

    /**
     * 和风天气签名生成算法-JAVA版本
     *
     * @param params 请求参数集，所有参数必须已转换为字符串类型
     * @param secret 签名密钥（用户的认证key）
     * @return 签名
     * @throws IOException
     */
    private String getSignature(HashMap<String, String> params, String secret) throws IOException {
        // 先将参数以其参数名的字典序升序进行排序
        Map<String, String> sortedParams = new TreeMap<>(params);
        Set<Map.Entry<String, String>> entrys = sortedParams.entrySet();

        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起

        StringBuilder baseString = new StringBuilder();
        for (Map.Entry<String, String> param : entrys) {
            //sign参数 和 空值参数 不加入算法
            if (param.getValue() != null && !"".equals(param.getKey().trim()) && !"sign".equals(param.getKey().trim()) && !"key".equals(param.getKey().trim()) && !"".equals(param.getValue().trim())) {
                baseString.append(param.getKey().trim()).append("=").append(param.getValue().trim()).append("&");
            }
        }
        if (baseString.length() > 0) {
            baseString.deleteCharAt(baseString.length() - 1).append(secret);
        }

        // 使用MD5对待签名串求签
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(baseString.toString().getBytes("UTF-8"));
            return   Base64.encodeToString(bytes,Base64.DEFAULT);
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
    }
}
